"""
Author: wenbin
Create: 2024-08-27
"""
from contextlib import contextmanager
from datetime import datetime

from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy
from sqlalchemy import Column, DateTime


class SQLAlchemy(_SQLAlchemy):

    @contextmanager
    def auto_commit(self):
        """
        自动提交
        """
        try:
            yield
            self.session.commit()
        except Exception as e:
            self.session.rollback()
            raise e


db = SQLAlchemy()


class BaseModel(db.Model):
    """
    基础模型
    """
    __abstract__ = True

    create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
    update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    delete_time = Column(DateTime, comment="删除时间")
